package com.wsz.oss.server.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.wsz.oss.server.OssService;
import com.wsz.oss.utils.OssUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = OssUtils.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = OssUtils.ACCESS_KEY_ID;
        String accessKeySecret = OssUtils.ACCESS_KEY_SECRET;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = OssUtils.BUCKET_NAME;
        try{

            String fileName = file.getOriginalFilename();

            String s = UUID.randomUUID().toString().replaceAll("-","");

            String datePath = new DateTime().toString("yyyy/MM/dd");

            fileName = datePath + "/" + s + fileName;

            InputStream inputStream = file.getInputStream();

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            ossClient.putObject(bucketName,fileName,inputStream);

            ossClient.shutdown();

            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;

            return url;

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}